<template>
	<view class="red-envelope-video-page"  :style="{
		'padding-top': statusBarHeight + 'px'
	}">
		<view class="rotate-wrap" v-if="isNeedDownTime">
			<rotate-count-down
				v-if="isNeedDownTime"
				:is-end="videoIsEnd"
				:is-pause="videoIsPause"
				:is-play="videoIsPlay"
				:video-down-time.sync="videoDownTime"
				:video-duration="videoDuration"/>
		</view>
		<swiper :circular="true" class="swipers" @change="change" :current="current" :vertical="true"
			:indicator-dots="false" :autoplay="false" :interval="3000" :duration="300" @touchEnd="touchEnd">
			<swiper-item class="swipers-item" v-for="(item,index) in swiperList" :key="item.courseDetailsId">
				<view class="swipers-items">
					<!-- 视频 -->
					<!-- v-if="current === index && item.videoUrl" -->
					<video 
						@timeupdate="timeupdate(item, $event)" 
						@waiting="waiting()" 
						object-fit="cover"
						v-if="current === index && item.videoUrl"
						:play-strategy="2" 
						:show-loading="true"
						codec="software" 
						:muted="viddeoMuted" 
						:show-center-play-btn="false" 
						:loop="false"
						@ended="ended"
						@play="videoPlay('myVideo'+item.courseDetailsId)" 
						@pause="pauseHandler"
						:enable-progress-gesture="false"
						@longpress="onLongPress" 
						@error="videoErrorCallback"
						:rate="playbackRate" 
						:poster="item.titleImg"
						:ref="'myVideo'+item.courseDetailsId" 
						:id="'myVideo'+item.courseDetailsId" 
						:src="item.videoUrl"
						:autoplay="item.autoPlay" 
						show-center-play-btn
						show-mute-btn	
						class="swipers-items-video"
						:style="{
							width: windowWidth + 'px',
						}"
					></video>
					<!-- :autoplay="item.autoPlay" -->
					<!-- 没有视频权限则显示封面图 -->
					<image v-else @click="showPay = true" :src="item.titleImg" class="swipers-items-imgsbg"
						mode="aspectFill"></image>
	
					<!-- 视频信息 -->
					<view class="swipers-items-info" v-if="true">
						<!-- 标题 -->
						<view class="swipers-items-info-title">
							{{item.courseDetailsName}}
						</view>
						<!-- 简介 -->
						<view class="swipers-items-info-content" v-html="item.content"></view>
						
					</view>
					
				</view>
			</swiper-item>
		</swiper>
		<tabbar />
		<!-- start 弹出一个弹窗 用来抽奖 -->
		<u-popup 
			v-model="lotteryVisible"
			width="100%"
			mode="center" 
			class="custom-mask lottery-popup"
			:mask="false"
		>
			<lottery-vue :list="redEnvelopeList" :select-id="activeRedEnvelopeInfo.red_id" @select="openLotteryDrawing" page-mod="popup">
				<view slot="footer">
					<button 
						size="default" 
						type="default" 
						style="color:#000;backgroundColor:#ff8200;borderColor:#1AAD19; border-radius: 50%;" 
						hover-class="is-hover"
						@click="closeLottery"
					>✕</button>
				</view>
			</lottery-vue>
		</u-popup>
		<!-- end 抽奖 -->
		
		<!-- start 开奖 弹出一个弹窗 用来开奖 -->
		<u-popup 
			v-model="lotteryDrawingVisible" 
			width="100%" 
			mode="center" 
			class="custom-mask lottery-drawing-popup"
		>
			<lottery-drawing-vue :text="activeRedEnvelopeInfo.money" @close="closeLotteryDrawing">
				
			</lottery-drawing-vue>
		</u-popup>
		<!-- end 开奖 -->
	</view>
</template>

<script>
	import mixin from "./mixin";
	import lottery_mixin from "./lottery_mixin"
	import rotateCountDown from './components/rotate_count_down.vue';
	import lotteryVue from './components/lottery.vue';
	import lotteryDrawingVue from './components/lottery_drawing.vue';
	import {
		apiVideoDetail,
		apiVideoUrl,
		apiVideoRecord
	} from '@/api/store'
	let wattingTimer = null
	export default {
		mixins: [mixin, lottery_mixin],
		components: {
			rotateCountDown,
			lotteryVue,
			lotteryDrawingVue
		},
		data() {
			return {
				customStyle: {
					background: '#202020'
				},
				isStart: false, //是否开始生成二维码
				viddeoMuted: false,
				erweima: '',
				qrCodeData: '',
				haibaoImg: '',
				showImg: false,
				haibaoShow: false,
				title: '',
				imgSrc: '',
				current: 0,
				playbackRate: 1.0,
				maskCustomStyle: {
					background: 'rgba(0, 0, 0, 0.5)'
				},
				show: false,
				videoList: [],
				videoContext: null, //记录当前视频的上下文
				isCollect: false,
				isVIP: false, //是否是vip
				courseId: '',
				meunList: [], //菜单
				meunTop: 0, //返回图标距离顶部的距离
				num: 1, //当前播放的集数
				showPay: false, //购买视频的弹窗
				info: {}, //整部的信息
				courseDetailsId: '', //详情id
				scrollIntoView: '', //当前播放视频的位置
				scrollIntoViews: 'video0', //当前播放视频的位置
				isVips: '否', //是否显示会员
				windowWidth: 0,
				windowHeight: 0,
				isWaiting: false,
				isMounted: false,
				videoPreTime: -1,
				platform: '',
				statusBarHeight: 0
			};
		},
		computed: {
			swiperList() {
				return this.videoList
			}
		},
		onLoad(e) {
			let that = this
			//获取设备的高度
			uni.getSystemInfo({
				success(res) {
					console.log('rre',res)
					//计算右侧操作拦的位置
					that.platform = res.platform
					that.statusBarHeight = res.statusBarHeight
					that.windowWidth = res.windowWidth
					that.windowHeight = res.windowHeight - res.statusBarHeight
					that.rightTop.top = res.screenHeight - (440 / 2) + 'rpx'
				},
				fail() {
					//如果获取屏幕的高度失败，那么位置默认设置为通用高度630rpx
					that.rightTop.top = '630rpx'
					console.log("sss qay")
				}
			})
			// 这里的代码，全部可以不要，
		},
		onHide() {
			clearTimeout(wattingTimer)
			wattingTimer = null
			if (this.videoContext) {
				this.videoContext.pause()
				this.videoContext.stop()
				this.videoContext = null
			}
		},
		onUnload() {
			if (this.videoContext) {
				this.videoContext.stop()
				this.videoContext = null
			}
		},
		onShow() {
			// 这里的代码，全部可以不要，
			const vm = this
			// console.log("onshow", this.isWaiting, this.videoList, this.current)
			// console.log("onshow current", this.current)
			this.isVips = uni.getStorageSync('isVips') ? uni.getStorageSync('isVips') : '否'
			
			if (!this.isWaiting && this.isMounted) {
				// console.log("理论上来说，只有hide之后再进来，才会打印")
				this.$nextTick(() => {
					vm.change(vm.current)
				})
			}
		},
		onReady() {
			// #ifdef MP-WEIXIN
			let info = uni.getMenuButtonBoundingClientRect()
			this.meunTop = info.top + ((info.height - 19) / 2)
			// #endif
			// #ifndef MP-WEIXIN
			this.meunTop = 37
			// #endif
		},
		watch: {
			
		},
		mounted() {
			this.isMounted = true
		},
		methods: {
			//播放进度变化回掉
			timeupdate(item, e) {
				//隐藏loding
				// uni.hideLoading()
				this.timeupdateHandler(item, e)
				// console.log("视频如果暂停了，还会进来吗？", e)
				// console.log("进度条更新了", e)
				if (this.isWaiting) {
					// 进度条是 250ms 回调一次，那么，暂停时，确实有可能会进来
					// 那么，这里要如何处理。
					// 这里给他一个机制，如果暂停了，还走，下次播放时，给他的进度条减一秒。
					const videoPreTime = Math.floor(e.detail.currentTime) - 1
					// 如果视频只走了几百毫秒，那就让他从头开始吧。
					this.videoPreTime = videoPreTime > 1 ? videoPreTime : 0
				}
			},
			waiting(...arg) {
				this.videoIsPause = true
				this.videoIsPlay = false
				uni.showLoading({
					title:'正在缓冲……',
					icon: 'loading'
				})
				const vm = this
				if (this.videoContext) {
					this.videoContext.pause()
				}
				this.isWaiting = true
				this.waitingHandler(arg)
				// web端这段代码生效，所以，干脆直接不用这种方式了
				// this.$u.debounce(this.waitingHandler, 4000)
			},
			waitingHandler(arg){
				const vm = this
				clearTimeout(wattingTimer)
				wattingTimer = null
				
				wattingTimer = setTimeout(() => {
					clearTimeout(wattingTimer)
					wattingTimer = null
					if (vm.videoContext) {
						vm.videoPreTime = -1
						vm.videoContext.play()
					}
				}, 4000)
				
				
			},
		
		
			onLongPress() {
				// 设置为2倍速播放
				this.playbackRate = 2.0;
			},
			/**
			 * @param {String} path //返回的二维码地址
			 */
			qrR(path) {
				this.qrCodeData = path
				this.haibaoShow = true

			},
			//生成失败
			posterError() {
				this.haibaoImg = ''
				this.showImg = false
				// 生成完成后初始化分享
				this.haibaoShow = false
				this.isStart = false
				this.imgSrc = ''
				uni.showToast({
					title: '海报生成失败',
					mask: false,
					duration: 2000,
					icon: "none"
				});
			},
			/**生成成功
			 * @param {String} img 成功回调的图片
			 */
			posterSuccess(img) {
				this.haibaoImg = img.tempFilePath
				this.showImg = true
				// 生成完成后初始化分享
				this.haibaoShow = false
				this.isStart = false
				this.imgSrc = ''
				uni.hideLoading()
				uni.showToast({
					title: '长按图片保存海报',
					mask: false,
					duration: 2000,
					icon: "none"
				});
			},
			//分享
			share(item) {
				this.imgSrc = item.titleImg
				// #ifndef MP-WEIXIN
				let urls = config.APIHOST2 + '/me/detail/detail?id=' + item.courseId + '&courseDetailsId=' + item
					.courseDetailsId + '&invitation=' + uni.getStorageSync('invitationCode')
				this.erweima = urls
				this.isStart = true
				// #endif


				// #ifdef MP-WEIXIN
				let that = this
				let data = {
					invitationCode: uni.getStorageSync('invitationCode') + ',' + item.courseId + ',' + item
						.courseDetailsId,
					page: 'me/detail/detail'
				}
				uni.downloadFile({
					url: config.APIHOST + '/app/invite/mpCreateQr?invitationCode=' + data.invitationCode +
						'&page=' + data.page,
					success(res) {
						if (res.statusCode === 200) {
							that.qrCodeData = res.tempFilePath
							that.haibaoShow = true
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '分享失败',
								icon: 'none'
							})
						}
					}
				})
				// #endif
			},
			/**
			 * @param {Object} type 类型 
			 * 1:购买整部视频
			 * 2:购买单集视频
			 */
			payVideo(type) {
				//处理数据跳转支付
			},
			//去开通会员
			goNav(url) {
				uni.navigateTo({
					url: url
				})
			},
			//收藏
			shoucang(item) {
				//此处调用收藏接口
				apiVideoRecord({
					id: item.courseId,
					item_id: item.courseDetailsId,
					is_chase: !this.isCollect
				}).then((res) => {
					this.isCollect = !this.isCollect;
				});
			},
			//点赞
			dianzan(item) {
				//此处调用点赞接口
			},
			
			
			
			
			// 资源详情（//此处获取视频的资源数据，处理数据）
			getDataList(id, courseDetailsId, type) {
				

			},
			//记录历史记录
			setHistor(courseId, courseDetailsId) {
				
			},
			//swiper上下切换事件
			/** 这里是 swiper 上下切换事件，但是，在代码中，
			 * 播放结束时，也会调用此方法，因此，所传入的参数必须要符合要求。假如所传的一个e是一个数字时，
			 * @param {number|Object} e
			 */
			change(e) {
				let current = this.current
				clearTimeout(wattingTimer)
				wattingTimer = null
				// 切换视频前，倒计时的总时长归零.
				// this.videoDuration = 0
				if (typeof e === 'number') {
					current = e
				}
				if (typeof e === 'object' && e.detail) {
					current = Number(e.detail.current)
				}
				//拿出当前的swiper索引
				// 根据courseDetailsId在meunList中找到这个数据的下标
				let indexs = -1;
				
				
				//控制播放
				this.startPlay(current)
				// 一定是后赋值。
				this.current = current
				//插入历史记录
				// this.setHistor(this.videoList[this.current].courseId, this.videoList[this.current].courseDetailsId)
			},
			startPlay(current) {
				try{
					const vm = this
					// 这里的 current 可能并不是 this.current
					const newCurrent = current || this.current
					if (this.videoList.length <= newCurrent) {
						// 这里说明当前索引值，已经大于视频列表的长度了，要么重新请求，要么就是已经是最后一条了。
						// 在这里，简单的认为他已经是最后一条了。不做处理, 在调用这个方法前，应该要做好处理。
						return
					}
					
					// 这里通常是停掉上一个视频，
					if (this.videoContext) { //判断之前是否有视频的上下文
						this.videoContext.stop()
						this.videoContext = null
					}
					
					// newCurrent 可能并不是 this.current，所以，这里需要延时执行。等新的数据更新之后,再来播放新的视频。
					vm.$nextTick(() => {
						//播放当前的
						// 重新给videoContext赋值。这里需要判断一下，是否有这个资源。
						const numIdCurr = this.videoList[newCurrent].courseDetailsId
						if (!numIdCurr) {
							return
						}
						vm.videoContextId = 'myVideo' + numIdCurr
						// console.log("this.videoContextId", 'can not find---',  this.videoContextId)
						// console.log("this.videoContextId", '--this.cur',  this.current, newCurrent)
						// console.log("this.videoContextId", '===videoPath',  this.videoList[this.current])
						vm.videoContext = uni.createVideoContext(vm.videoContextId, vm)
						setTimeout(() => {
							if (vm.videoContext && vm.videoContext.play) {
								// this.viddeoMuted = false
								
								vm.videoContext.play()
								vm.$forceUpdate()
							}
						}, 500)
					})
				}catch(e){
					console.log("去啊一块", e)
					//TODO handle the exception
				}
				
			},
			//播放时的回调
			videoPlay(videoId) {
				uni.hideLoading()
				this.videoIsPause = false
				this.videoIsPlay = true
				this.isWaiting = false
				clearTimeout(wattingTimer)
				wattingTimer = null
				this.videoStartLotteryHandler()

			},
			//监听视频播放完成
			ended() {
				this.isWaiting = false
				clearTimeout(wattingTimer)
				wattingTimer = null
				this.videoEndLotteryHandler()
			},
			pauseHandler(e) {
				this.videoIsPause = true
			},
			
			touchEnd() {
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #000;
	}
	.red-envelope-video-page {
		display: flex;
		flex-direction: column;
		width: 750rpx;
		height: 100vh;
		
	}

	/deep/.u-drawer-bottom {
		background-color: #202020 !important;
	}

	

	.swipers {
		width: 100vw;
		height: calc(100vh - 102rpx);
		
		.swipers-item {
			width: 100%;
			height: 100%;
		}

		.swipers-items {
			position: relative;
			width: 100%;
			height: 100%;
			
		}
		.swipers-item:nth-child(odd) {
			// background-color: red;
		}
		.swipers-items-imgsbg {
			position: absolute;
			width: 100%;
			height: 100%;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.swipers-items-video {
			width: 100%;
			height: calc(100vh - 102rpx);
		}

		.swipers-items-back {
			position: absolute;
			top: 20rpx;
			left: 20rpx;
			z-index: 999;
		}

		.swipers-items-info {
			position: absolute;
			width: 80%;
			height: auto;
			bottom: 100rpx;
			left: 20rpx;
			color: #ffffff;
			font-size: 30rpx;
			z-index: 999;

			.swipers-items-info-content {
				margin-top: 10rpx;
				font-size: 26rpx;
			}

			.swipers-items-info-num {
				margin-top: 20rpx;
			}
		}

		.swipers-items-right {
			position: absolute;
			width: 60rpx;
			
			right: 20rpx;
			top: 70%;
			transform: translate(0, -70%);
			z-index: 999;

			.swipers-items-right-item {
				width: 100%;
				margin-bottom: 40rpx;
			}

			.swipers-items-right-item-img {
				image {
					width: 60rpx;
					height: 60rpx;
				}
			}

			.swipers-items-right-item-txt {
				width: 100%;
				text-align: center;
				font-size: 24rpx;
				color: #ffffff;
				font-weight: bold;
				margin-top: 10rpx;
			}
		}
	}
</style>

<style style="scss">
	
	.custom-mask {
		
		::v-deep.u-drawer-content {
			background-color: rgba(0, 0, 0, 0.7) !important;
		}
		
		/deep/ .u-drawer-right {
			background-color: rgba(0, 0, 0, 0.7);
		}
	}
	.uni-video-bar {
		bottom: 110rpx;
		z-index: 99999 !important;
	}
</style>